package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.heima.api.schedule.IScheduleClient;
import com.heima.common.constant.TaskTypeEnum;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.schedule.dto.TaskDto;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class)
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 延时审核发布文章
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        // 查询文章对象
        WmNews wmNews = wmNewsMapper.selectById(id);

        TaskDto task = new TaskDto();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        // 把文章对象存入参数位置，消费时可以拿出文章对象进行审核发布
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
    }

    @Scheduled(fixedRate = 5000)
    public void scanNews() throws Exception {
        ResponseResult result = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result != null && result.getCode() == 200 && result.getData() != null) {
            // 消费成功，从redis的list中拿出一个待执行的审核任务
            TaskDto task = (TaskDto) result.getData();
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            // 执行审核逻辑，并发布文章
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
    }
}
